<?php


namespace App\Http\Controllers\Mini\Circle;


use App\Http\Controllers\Controller;
use App\Models\FleaCollectionGoods;
use App\Models\FleaNotice;
use App\Models\FleaOrder;
use App\Models\Mini\FleaGoodsModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FleaCollectionGoodsController extends Controller
{
    private $user_id;

    public function __construct()
    {
        $id = auth('user')->id();
        $this->user_id = $id;
    }

    /**
     * @param Request $request
     * 获取我的收藏列表
     */
    public function index(Request $request)
    {
        $user_id = $this->user_id;

        if (!$user_id) {
            return $this->error('请先登录');
        }

        $data = FleaCollectionGoods::query()->where('user_id', $user_id)->value('goods_ids') ?? '[]';
        $goods_ids = json_decode($data, true);

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;

        $data = FleaGoodsModel::query()->whereIn('id', $goods_ids)->offset($offset)->limit($limit)->get();

        $response['data'] = $data;
        $response['count'] = FleaGoodsModel::query()->whereIn('id', $goods_ids)->count();
        $response['pages'] = ceil($response['count'] / $limit);

        return $this->success($response, '请求成功');
    }

    /**
     * @param Request $request
     * @return array
     * 收藏 / 取消收藏
     */
    public function collectionGoods(Request $request)
    {
        $user_id = $this->user_id;

        if (!$user_id) {
            return $this->error('请先登录');
        }

        $goods_id = $request->post('goods_id');

        if (!$goods_id) {
            return $this->error('参数错误');
        }

        //获取用户已经点赞过的商品
        $data = FleaCollectionGoods::query()->where('user_id', $user_id)->value('goods_ids') ?? '[]';
        $data = json_decode($data, true);

        if (in_array($goods_id, $data)) {
            $msg = '已取消收藏';
            $key = array_search($goods_id, $data);
            unset($data[$key]);
        } else {
            //声明一个变量判断是否是收藏
            $state = true;
            //收藏成功
            $msg = '收藏成功';
            array_push($data, $goods_id);
        }
        $insert = ['goods_ids' => json_encode($data)];

        //查询发布商品的用户是谁
        $goods_user_id = FleaGoodsModel::query()->where('id', $goods_id)->value('user_id');

        DB::beginTransaction();
        try {
            if (isset($state)) {
                //如果通知的人是登录的人，那就不用通知了
                if ($goods_user_id != $user_id) {
                    //收藏
                    $create = [
                        'type' => 1,  // 1收藏  2留言  3订单评论  4提现
                        'msg' => '收藏了你的发布',
                        'goods_id' => $goods_id, //邻里圈跳蚤市场商品ID
                        'user_id' => $goods_user_id, //被通知人ID
                        'user_from_id' => $user_id //来自谁的通知用户ID
                    ];
                    //记录通知
                    FleaNotice::query()->create($create);
                }

                FleaGoodsModel::query()->where('id', $goods_id)->increment('goods_collect');
            } else {
                FleaGoodsModel::query()->where('id', $goods_id)->decrement('goods_collect');
            }

            FleaCollectionGoods::query()->updateOrInsert(['user_id' => $user_id], $insert);

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success([], $msg);

    }


    /**
     * @param Request $request
     * 获取我的消息通知列表
     */
    public function notice(Request $request)
    {
        $user_id = $this->user_id;

        if (!$user_id) {
            return $this->error('请先登录');
        }

        $type = $request->get('type', 1);

        $where[] = ['classify', '=', $type];

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;

        if ($type == 1) {
            $data = FleaNotice::query()->with(['goods:id,goods_name,goods_images', 'user:id,nickname,username,avatar'])->where('user_id', $user_id)->where($where)->orderByDesc('id')->offset($offset)->limit($limit)->get();
        } elseif($type == 2) {
            $data = FleaNotice::query()->where('user_id', $user_id)->where($where)->orderByDesc('id')->select('id', 'type', 'msg', 'user_id', 'created_at', 'read_at')->offset($offset)->limit($limit)->get();
        }

        $response['data'] = $data;
        $response['count'] = FleaNotice::query()->where($where)->where('user_id', $user_id)->count();
        $response['pages'] = ceil($response['count'] / $limit);

        return $this->success($response, '请求成功');
    }

    //删除消息通知
    public function destroyNotice($id)
    {
        $user_id = $this->user_id;

        if (!$user_id) {
            return $this->error('请先登录');
        }

        $res = FleaNotice::query()->where(['id' => $id, 'user_id' => $user_id])->delete();

        return $res ? $this->success([], '删除成功') : $this->error();
    }

    //标记为已读
    public function readNotice(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $ids = $request->get('ids');
        $ids = explode(',', $ids);

        $res = FleaNotice::query()->whereIn('id', $ids)->update(['read_at' => date('Y-m-d H:i:s')]);

        if ($res) {
            return $this->success([], '标记成功');
        }
        return $this->error();
    }

    //获取我发布的商品信息统计
    public function getMyDataCount()
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        //查询我发布的所有商品ID
        $goods_ids = FleaGoodsModel::query()->where('is_sale', '<>', 5)->where('user_id', $user_id)->pluck('id');
        $where[] = ['state', '<>', 1];
        //我卖出的
        $sellOut = FleaOrder::query()->whereIn('goods_id', $goods_ids)->where($where)->count();
        //我买到的
        $myBuy = FleaOrder::query()->where($where)->where('user_id', $user_id)->count();
        //我发布的
        $myGoods = count($goods_ids);
        //我收藏的
        $myCollectionGoods = FleaCollectionGoods::query()->where('user_id', $user_id)->value('goods_ids') ?? '[]';
        $myCollectionGoods = json_decode($myCollectionGoods, true);
        $myCollection = count($myCollectionGoods);
        return $this->success(compact(['sellOut', 'myBuy', 'myGoods', 'myCollection']));
    }

    //获取我未读信息统计
    public function getMyNotReadNotice()
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $systemNotice = FleaNotice::query()->where('user_id', $user_id)->where('classify', 2)->whereNull('read_at')->count();
        $userNotice = FleaNotice::query()->where('user_id', $user_id)->where('classify', 1)->whereNull('read_at')->count();

        return $this->success(['systemNotice' => $systemNotice, 'userNotice' => $userNotice]);

    }
}
